package Algorithm.BinarySearchNoRecursion;

public class BinarySearchNoRecur {
    public static void main(String[] args) {
        int[] arr = {1, 3, 8, 10, 11, 67, 100};
        int index = binarySearch(arr, 1);
        System.out.println("index = " + index);
    }

    //二分查找的非递归实现
    //arr 待查找数组 arr是升序
    //target 需要查找的数
    //返回对应下标 -1表示没有找到
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {//说明可以继续查找
            int mid = (left + right) / 2;
            if (arr[mid] == target) {
                return mid;
            }else if (arr[mid] > target) {//需要向左查找
                right = mid - 1;
            }else {
                left = mid + 1;
            }
        }
        return -1;
    }
}
